package android.bluebox.model;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class KeyCrypto {
	
	private String secretKey;
	private int iterationCount = 2020;
	
	private Crypto3 blueCrypto;
	
	public void init(PasswordCrypto passwordCrypto) {
		String encryptedKey = StaticBox.dbBox.getSystemKey();
		secretKey = passwordCrypto.decrypt(encryptedKey);
		blueCrypto = new Crypto3(secretKey, StaticBox.getSalt(), iterationCount);
	}

	public void initRandomKey(PasswordCrypto passwordCrypto) {

		// generate super secret key and encrypt it by using PasswordCrypto
		try {
			SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
			secretKey = new Integer(prng.nextInt()).toString();
			String encryptedKey = passwordCrypto.encrypt(secretKey);
			StaticBox.dbBox.updateSystemKey(encryptedKey);
		} catch (NoSuchAlgorithmException e) {
		}
	}
	
	public String getMD5Key() {
		return Crypto3.createMD5(secretKey);
	}

	public String encrypt(String str) {
		return blueCrypto.encrypt(str);
	}

	public String decrypt(String str) {
		return blueCrypto.decrypt(str);
	}
}
